/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nachos.network;
import nachos.threads.*;
import java.util.LinkedList;
/**
 *
 * @author cow
 */
public class window {
	//vars------------------------
	private MailMessage readfrom;
	private int offset;
	public Lock access;
	private int size;
	public LinkedList<MailMessage> packets;
	//----------------------------
	public window(int _size){
		size = _size;
		packets = new LinkedList<MailMessage>();
		access = new Lock();
	}
	public boolean add(MailMessage msg){
		if(msg != null){
			access.acquire();
			if(packets.size() < size){
				packets.addLast(msg);
				access.release();
				return true;
			} else {
				access.release();
				return false;
			}
		}
		return false;
	}
	public void remove(){
		access.acquire();
		if(notempty()) packets.remove();
		access.release();
	}
	public int read(byte[] bt, int bytes){
		access.acquire();
		int count = 0;
		if(readfrom == null){
			if(!packets.isEmpty()) readfrom = packets.pop();
		}
		while (bytes > 0 && readfrom != null) {
			for (int i = 0; i + offset < readfrom.contents.length; i++) {
				bt[i] = readfrom.contents[i + offset];
				bytes--;
				count++;
			}
			if(notempty()){
				readfrom = packets.pop();
			}
		}
		access.release();
		return count;
	}
	public int size(){
		return packets.size();
	}
	public int maxSize(){
		return size;
	}
	public boolean notempty(){
		return !packets.isEmpty();
	}
}
